package org.syntaxlisp.core;

import org.syntaxlisp.core.element.ReservedTag;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @author HuangYijun
 * @data 2023-01-10 11:11
 **/
public class LispStyleAccess {

    public static void make(String normalizeSrcPath, String normalizeOutPath, String simplifyOutPath) throws IOException {
        String base = LispStyleAccess.class.getResource("/").getPath();
        normalize(base + File.separator + normalizeSrcPath, base + File.separator + normalizeOutPath);
        simplify(base + File.separator + normalizeOutPath, base + File.separator + simplifyOutPath);
        checkBaseAndEntry (base + File.separator + simplifyOutPath);
    }

    public static void checkBaseAndEntry(String syntaxPath) throws FileNotFoundException {
        List<Element> defElements = LispListParser.parse(readAll(syntaxPath));
        Map<String, Set<String>> refMap = new HashMap<>();
        Set<String> tokenSet = new HashSet<>();
        for (Element defElement : defElements) {
            Set<String> refSet = new HashSet<>();
            String defName = defElement.getSubItems().get(1).getValue();
            refMap.put(defName, refSet);
            collectBases(defElement.getSubItems().get(2), refSet, tokenSet);
            if (refSet.isEmpty()) {
                System.out.printf("Def Base : %s\n", defName);
            }
            if (refSet.size() == 1 && refSet.contains(defName)) {
                System.out.printf("Self-ref Base : %s\n", defName);
            }
        }
        Set<String> noDefBases = new HashSet<>();
        refMap.forEach((defName, refs) ->
//            System.out.printf("Def ref : %s -> %s\n", defName, refs);
            refs.forEach(ref -> {
                if (!refMap.containsKey(ref)) {
                    noDefBases.add(ref);
                }
            })
        );
        System.out.printf("Base Tokens : %s\n", tokenSet);
        System.out.printf("No-def bases : %s\n", noDefBases);
        Set<String> entries = new HashSet<>();
        refMap.forEach((defName, refs) -> {
            boolean isEntry = true;
            for (Map.Entry<String, Set<String>> defEntry : refMap.entrySet()) {
                if (defEntry.getValue().contains(defName)) {
                    isEntry = false;
                    break;
                }
            }
            if (isEntry) {
                entries.add(defName);
            }
        });
        System.out.printf("entries: %s\n", entries);
    }

    private static void collectBases(Element cur, Set<String> bases, Set<String> baseToken) {
        if (cur.getElementType() == ElementType.LIST) {
            cur.getSubItems().forEach(item -> collectBases(item, bases, baseToken));
        } else if (cur.getElementType() == ElementType.TOKEN) {
            if (!ReservedTag.isReservedTag(cur.getValue())) {
                bases.add(cur.getValue());
            }
        } else {
            baseToken.add(cur.getValue());
        }
    }

    public static String readAll (String filePath) throws FileNotFoundException {
        File cf = new File(filePath);
        StringBuilder builder = new StringBuilder();
        Scanner sc = new Scanner(cf, StandardCharsets.UTF_8.name());
        while (sc.hasNextLine()) {
            String cur = sc.nextLine();
            if (!cur.startsWith("#")) {
                builder.append(cur);
            }
        }
        sc.close();
        return builder.toString();
    }

    private static void simplify (String inputPath, String outPath) throws IOException {
        File outFile = new File(outPath);
        if (!outFile.exists()
                && !outFile.createNewFile()) {
            return;
        }
        OutputStream outputStream = new FileOutputStream(outFile);

        List<Element> defElements = LispListParser.parse(readAll(inputPath));
//        List<Element> simplifiedElements = LispListParser.parse(readAll());
        for (Element defElement : defElements) {
            System.out.printf("Simplifying %s\n", defElement.getSubItems().get(1).getValue());
            Element simplified = simplify0 (defElement);
            System.out.println();
            outputStream.write(simplified.toString().getBytes(StandardCharsets.UTF_8));
            outputStream.write("\r\n".getBytes(StandardCharsets.UTF_8));
        }
        outputStream.close();
    }

    private static Element simplify0(Element element) {
        if (element.getElementType() == ElementType.LIST) {
            if (element.getSubItems().size() > 1) {
                if ((ReservedTag.ALTERNATIVE.isMatch(element.getSubItems().get(0).getValue())
                        || ReservedTag.SEQ_CONNECT.isMatch(element.getSubItems().get(0).getValue()))
                        && element.getSubItems().size() == 2) {
                    if (ReservedTag.ALTERNATIVE.isMatch(element.getSubItems().get(0).getValue())) {
                        System.out.println("OR simplified happened!");
                    } else {
                        System.out.println("& simplified happened!");
                    }
                    return simplify0(element.getSubItems().get(1));
                } else {
                    Element simplifiedElement = new Element();
                    simplifiedElement.setElementType(ElementType.LIST);
                    simplifiedElement.setSubItems(new ArrayList<>());
                    for (Element sub : element.getSubItems()) {
                        simplifiedElement.getSubItems().add(simplify0(sub));
                    }
                    return simplifiedElement;
                }
            } else {
                throw new RuntimeException ("syntax error!");
            }
        } else {
            return element;
        }
    }

    private static void normalize (String inPath, String outPath) throws IOException {
        File f = new File(inPath);
        File outFile = new File(outPath);
        if (!outFile.exists()
                && !outFile.createNewFile()) {
            return;
        }
        try (OutputStream outputStream = new FileOutputStream(outFile)) {
            try (Scanner inSc = new Scanner(f)) {
                while (inSc.hasNextLine()) {
                    String defName = inSc.nextLine();
                    if (defName.endsWith(":")) {
                        outputStream.write(("(" + "DEF" + " " + defName.substring(0, defName.length() - 1) + " " + inSc.nextLine() + ")")
                                                   .getBytes(StandardCharsets.UTF_8));
                        outputStream.write("\r\n".getBytes(StandardCharsets.UTF_8));
                        outputStream.write("\r\n".getBytes(StandardCharsets.UTF_8));
                    }
                }
            }
        }
    }

}
